/**
 * 权限
 */

import ApiApp from "@/api/app";
import useAppStore from "@/store";
import request from "@/utils/request";
import { useMount } from "ahooks";

export default () => {
  const authRoles = useAppStore((state) => state.authRoles);
  const setAuthRoles = useAppStore((state) => state.setAuthRoles);

  useMount(async () => {
    if (!authRoles) {
      const { list } = (await request({ url: ApiApp.getByRole })) as {
        list: any;
      };
      setAuthRoles(list);
    }
  });

  const getAuth = (prcode: undefined | string | string[]) => {
    if (prcode) {
      const list = Array.isArray(prcode) ? prcode : [prcode];
      return !!list.find((e) => authRoles?.has(e));
    }
    return true;
  };

  return getAuth;
};
